package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.User;
import com.weilai.service.CaptchaService;
import com.weilai.service.EmailService;
import com.weilai.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;


@Controller
@Api(tags = "验证码登录", description = "提供验证码登录方法的接口")
@RequestMapping("/login")
public class LoginCodeController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;
    @Autowired
    private CaptchaService captchaService;

    @ApiOperation(value = "验证码登录方法", notes = "验证码登录方法，需要输入用户邮箱和验证码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录成功")
    })
    //验证码登录
    @PostMapping("/loginCode")
    public ModelAndView login(@RequestParam String email, @RequestParam String code,
                              HttpServletRequest request, RedirectAttributes redirectAttributes) {
        HttpSession session = request.getSession();
        try {
            session.setAttribute("loginCodeEmail", "");

            ModelAndView mav = new ModelAndView();
            User user = userService.getUserByEmail(email);

            // 用户不存在检查
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "无此用户，请创建用户后再登录");
            }

            // 验证码校验
            if (captchaService.getByEamil(email)==null || !code.equals(String.valueOf(captchaService.getByEamil(email).getCaptchaCode()))) {
                session.setAttribute("loginCodeEmail", email);
                throw new BusinessException(Code.PROJECT_BUSINESS_ERROR, "验证码错误，请重试");
            }

            // 登录成功处理
            session.setAttribute("userId", user.getId());
            user.setPassword("****");
            session.setAttribute("user", user);

            // 根据角色跳转不同页面
            if ("admin".equals(user.getRole())) {
                mav.setViewName("redirect:/mainPageRecommend");
            } else {
                mav.setViewName("redirect:/mainPageRecommend");
            }
            session.removeAttribute("loginCodeEmail");

            return mav;

        } catch (BusinessException e) {
            session.setAttribute("loginCodeEmail", email);
            // 业务异常处理
            throw e;
        } catch (Exception e) {
            session.setAttribute("loginCodeEmail", email);
            // 系统异常处理
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "登录系统异常", e);
        }
    }

    @ApiOperation(value = "发送验证码方法", notes = "发送验证码，需要输入用户邮箱")
    @ApiResponses({
            @ApiResponse(code = 200, message = "发送成功")
    })
    //发送验证码
    @PostMapping("/loginCode/sendCode")
    public ModelAndView sendCode(@RequestParam String email, HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
            session.setAttribute("loginCodeEmail", "");
            ModelAndView mav = new ModelAndView();

            // 检查用户是否存在
            User user = userService.getUserByEmail(email);
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该邮箱未注册，请先注册");
            }

            //发送验证码
            captchaService.sendCode(email);

            mav.addObject("result", "验证码已发送至您的邮箱");
            mav.setViewName("login");
            session.removeAttribute("loginCodeEmail");
            return mav;
        } catch (BusinessException e) {
            session.setAttribute("loginCodeEmail", email);
            throw e;
        } catch (Exception e) {
            session.setAttribute("loginCodeEmail", email);
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "发送验证码过程中出现系统错误", e);
        }
    }
}
